package com.credit.mola.app.app

import android.annotation.SuppressLint
import android.content.Context
import com.credit.mola.app.BuildConfig
import com.credit.mola.app.analysis.TestAnalysisInit
import com.credit.mola.app.base.BaseApp
import com.credit.mola.app.ui.permission.PermitUtil
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.event.track.TrackEventManager
import com.credit.mola.app.utils.http.HttpHelper
import com.credit.mola.app.utils.http.OkHttpLoader
import com.credit.mola.app.utils.log.HHLog
import com.credit.mola.app.utils.sp.SPUtils
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty


/**
 * Sikadwa
 * @Author：wwdeng
 * @CreateTime：2024/4/14 19:27
 * <pre>
 *
 * </pre>
 */
class App: BaseApp() {

    companion object {

        private var instance: App by NotNullSingleValueVar()
        fun instance() = instance

        @SuppressLint("StaticFieldLeak")
        lateinit var app: App
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        app = this
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        //保存加解密key
        Configs.saveSPString(Configs.SPKEY.CREDIT_MOLA_KEY, "niCjDs5lRy5s1j52")
        Configs.saveSPString(Configs.SPKEY.CREDIT_MOLA_IV, "JEE4mozk6X6rz848")
        initLibConfigs()
    }

    override fun onTerminate() {
        TrackEventManager.destroy()
        super.onTerminate()
    }

    /**
     * 初始化Lib
     */
    private fun initLibConfigs(){
        HHLog.debug(BuildConfig.isDebug)
        HttpHelper.init(OkHttpLoader())
        //初始化读取所有权限
        PermitUtil.readPermitManager(SPUtils.getAppSp())
        //初始化 analysis
        TestAnalysisInit.initAnalysisLibAtAppLaunch()

        //初始化批量埋点工具
        TrackEventManager.init(this)
    }

    /**
     * 获取当前手机屏幕的宽
     */
    fun getPhoneWidth(): Int {
        // 手机屏幕的宽
        // 获取DisplayMetrics对象
        val displayMetrics = instance().resources.displayMetrics
        return displayMetrics.widthPixels
    }

    public fun getPhoneHeight(): Int {
        // 手机屏幕的高
        // 获取DisplayMetrics对象
        val displayMetrics = instance().resources.displayMetrics
        return displayMetrics.heightPixels
    }

    //定义一个属性管理类，进行非空和重复赋值的判断
    private class  NotNullSingleValueVar<T>() : ReadWriteProperty<Any?, T> {
        private var value: T? =null
        //非空的校验
        override fun getValue(thisRef: Any?, property: KProperty<*>): T {
            return value ?: throw IllegalArgumentException("application not initialized")
        }
        //重复赋值的校验
        override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
            this.value=if (this.value==null) value
            else throw IllegalArgumentException("application already initialized")
        }
    }
}